import Vue from "vue";
import Vuex from "vuex";
import { loginApi } from "@/api/login";
import Persist from "vuex-persist";
Vue.use(Vuex);
var persist = new Persist({
  storage: window.sessionStorage,
});
export default new Vuex.Store({
  // 严格模式
  strict: true,
  state: {
    userInfo: {
      id: "",
      rid: "",
      username: "",
      mobile: "",
      email: "",
    },
    token: "",
  },
  getters: {},
  mutations: {
    // 设置手机号
    SET_MOBILE(state, value) {
      state.userInfo.mobile = value;
    },
    // 设置rid
    SET_RID(state, value) {
      state.userInfo.rid = value;
    },
    // 设置id
    SET_ID(state, value) {
      state.userInfo.id = value;
    },
    // 设置邮箱
    SET_EMAIL(state, value) {
      state.userInfo.email = value;
    },
    // 设置用户名
    SET_USERNAME(state, username) {
      state.userInfo.username = username;
    },
    // 设置token
    SET_TOKEN(state, token) {
      state.token = token;
    },
  },
  actions: {
    // 登录
    LOGIN({ commit }, data) {
      return loginApi(data).then(({ data }) => {
        var { data } = data;
        var { id, rid, username, mobile, email, token } = data;
        commit("SET_TOKEN", token);
        commit("SET_MOBILE", mobile);
        commit("SET_RID", rid);
        commit("SET_ID", id);
        commit("SET_USERNAME", username);
        commit("SET_EMAIL", email);
        return data;
      });
    },
    // 退出登录
    OUT({ commit }) {
      commit("SET_TOKEN", "");
      commit("SET_MOBILE", "");
      commit("SET_RID", "");
      commit("SET_ID", "");
      commit("SET_USERNAME", "");
      commit("SET_EMAIL", "");
    },
  },
  plugins: [persist.plugin],
  // vuex模块管理
  modules: {
    // goods模块只给goods页面使用
    goods: {
      // 开启命名空间，让当前的模块有自己的名称
      namespaced: true,
      state: {
        // 预备添加的产品信息
        newGoods: {},
      },
      mutations: {
        SET_GOODS(state, form) {
          console.log("我被触发了", form);
          state.newGoods = form;
        },
      },
      actions: {
        SEND_ADD_GOODS({ commit }, data) {
          // axios接口：添加商品的接口
        },
      },
    },
  },
});
